package controller

import (
	"fmt"
	"io/fs"
	"os"
	"path"
	"tk-gen/global"
	"tk-gen/types"

	"github.com/duke-git/lancet/v2/fileutil"
)

func TreeFile() ([]types.FileTree, error) {
	return getFileTree(global.DataDir, "")
}
func CreateFile(filename string) error {
	if fileutil.CreateFile(path.Join(global.DataDir, filename)) {
		return nil
	}
	return fmt.Errorf("创建文件失败")
}
func CreateDir(filename string) error {
	return fileutil.CreateDir(path.Join(global.DataDir, filename))
}
func CopyFile(filename string) error {
	return fileutil.CopyFile(path.Join(global.DataDir, filename), path.Join(global.DataDir, filename+" copy"))
}
func CopyDir(filename string) error {
	return fileutil.CopyDir(path.Join(global.DataDir, filename), path.Join(global.DataDir, filename+" copy"))
}
func ReadFile(filename string) (string, error) {
	return fileutil.ReadFileToString(path.Join(global.DataDir, filename))
}
func WriteFile(filename string, content string) error {
	return fileutil.WriteStringToFile(path.Join(global.DataDir, filename), content, false)
}
func RenameFile(oldpath string, newpath string) error {
	return os.Rename(path.Join(global.DataDir, oldpath), path.Join(global.DataDir, newpath))
}
func RemoveFile(filename string) error {
	return fileutil.RemoveFile(path.Join(global.DataDir, filename))
}

func getFileTree(dir string, filename string) ([]types.FileTree, error) {
	var err error
	var children []os.DirEntry
	var items []types.FileTree
	children, err = os.ReadDir(dir)
	if err != nil {
		return items, err
	}
	for _, f := range children {
		if filename == "" && !f.IsDir() {
			continue
		}
		var info fs.FileInfo
		info, err = f.Info()
		if err != nil {
			break
		}
		item := types.FileTree{
			Dir:     filename,
			Path:    path.Join(filename, f.Name()),
			Name:    info.Name(),
			Size:    info.Size(),
			ModTime: info.ModTime(),
			IsDir:   info.IsDir(),
		}
		if item.IsDir {
			item.Children, err = getFileTree(path.Join(dir, item.Path), item.Path)
			if err != nil {
				break
			}
		}
		items = append(items, item)
	}
	return items, err
}
